import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from "@angular/http";
import {LoadingService} from "../loading/loading.service";
import {UploadFileForm} from "./models/uploadFileForm";
import 'rxjs/add/operator/toPromise';
import {PromptService} from "../prompt/prompt.service";
import {CommonService} from "../common.service";

declare var toastr: any;
@Injectable()
export class HttpService {

    constructor(private http: Http, private loadingService: LoadingService, private promptService: PromptService, private commonService: CommonService) {

    }

    post(url: string, body: any): Promise<any> {
        // console.log(body)
        var promise = new Promise<any>(resolve=> {
            let headers = new Headers({'Content-Type': 'application/json'});
            let options = new RequestOptions({headers: headers});
            this.loadingService.start()
            // console.log( JSON.stringify(body))
            // this.http.post(this.commonService.getRequestProUrl() + url, JSON.stringify(body), options).toPromise().then((response:any) => {
            //     // console.log(response.json())
            //     this.loadingService.end()
            //     resolve(response.json())
            // }).catch((error: any)=> {
            //     this.loadingService.end()
            //     // this.promptService.warning(JSON.parse(error._body).error.message)
            // });

            this.http.post(this.commonService.getRequestProUrl() + url, JSON.stringify(body),options).subscribe(
                response=>{
                    this.loadingService.end()
                    resolve(response.json())
                },
                error=>{
                    this.loadingService.end()
                }
            )
        })


        return promise;


    }

    uploadFile(file: File): Promise<any> {
        let url: string = "/api/file/upload_file"
        let uploadFileForm: UploadFileForm = new UploadFileForm(file)
        console.log(uploadFileForm)
        return this.post(url, uploadFileForm);
    }
}